package com.nway.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExceptionHandleFilter implements Filter {

	private static final Logger logger = LoggerFactory
			.getLogger(ExceptionHandleFilter.class);

	private String exceptionHandlePath = "error.jsp";

	public void init(FilterConfig config) throws ServletException {
		String customPath = config.getInitParameter("path");

		if (null != customPath || !"".equals(customPath)) {
			exceptionHandlePath = customPath;
		}
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		try {
			chain.doFilter(request, response);
		} catch (Exception e) {

			StringBuilder exTrace = new StringBuilder();
			for (StackTraceElement trace : e.getStackTrace()) {
				exTrace.append(trace.toString()).append("\n");
			}

			request.setAttribute("exceptionMsg", e.getLocalizedMessage());
			request.setAttribute("exceptionTrace", exTrace);

			logger.error(e.toString(), e);

			request.getRequestDispatcher(exceptionHandlePath).forward(request,
					response);
		}
	}

	public void destroy() {

	}

}
